<?php

namespace log;

use MongoDB\Driver\BulkWrite;
use MongoDB\Driver\Manager;

class Mongo
{
    private $manager;
    private $conf;

    // 实例化并传入参数
    public function __construct($config = [])
    {
        $config = config('mongo');
        $this->conf = $config;
        //动态化配置
        $this->manager = new Manager("mongodb://{$config['username']}:{$config['password']}@{$config['host']}:{$config['port']}/{$config['database']}");
    }

    /**
     * 日志写入接口
     * @access public
     * @param array $log 日志信息
     * @param bool $depr 是否写入分割线
     * @return bool
     */
    public function save(array $log = [], $depr = true)
    {
        $addTime = date('Y-m-d H:i:s');
        $errArr = [];
        foreach ($log as $type => $error) {
            foreach ($error as $msg) {
                $errArr[] = [
                    'add_time' => $addTime,
                    'type' => $type,
                    'msg' => $msg
                ];
            }
        }

        $database = "bs_log";
        $collection = "error_log";

        $res = null;
        foreach ($errArr as $item) {
            // 构建插入操作
            $bulk = new BulkWrite;
            $bulk->insert($item);

            // 执行插入操作
            $res[] = $this->manager->executeBulkWrite("$database.$collection", $bulk);
        }

        return true;
    }

    /**添加的静态方法
     * @param array|string|object $log 任何内容
     * @param string $type 自定义标识
     * @return bool
     * @example \log\Mongo::add($baseData,'contract_add');     *
     */
    public static function add($log, $type = 'debug')
    {
        return (new self())->diy($log, $type);
    }

    public function diy($log, $type = 'error')
    {
        $data = [
            'add_time' => date('Y-m-d H:i:s'),
            'type' => $type,
            'log' => is_array($log) || is_object($log) ? json_encode($log, JSON_UNESCAPED_UNICODE) : $log
        ];

        $database = $this->conf['database'];
        $collection = $this->conf['collection_log'];
        // 构建插入操作
        $bulk = new BulkWrite();
        $bulk->insert($data);

        // 执行插入操作
        $this->manager->executeBulkWrite("$database.$collection", $bulk);

        return true;
    }
}
